<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>其他出库单</title>
    <script src="static/js/jquery-3.6.0.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }

        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            text-align: center;
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-top: 10px;
            font-weight: bold;
        }

        input[type="text"],
        select,
        input[type="date"],
        input[type="file"],
        input[type="number"] {
            width: calc(100% - 20px);
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th,
        td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: center;
        }

        th {
            background-color: #f2f2f2;
        }

        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
            margin-right: 10px;
            border-radius: 5px;
        }

        button:hover {
            background-color: #0056b3;
        }

        .submit-button {
            text-align: right;
            margin-top: 20px;
        }

        .preview {
            display: flex;
            align-items: center;
            margin-top: 10px;
        }

        .preview img {
            width: 100px;
            height: 100px;
            margin-right: 10px;
            object-fit: cover;
            border-radius: 5px;
        }

        .preview span {
            margin-right: 10px;
        }

        .delete-btn {
            color: red;
            cursor: pointer;
        }

        #message {
            padding: 10px;
            margin-top: 10px;
            border-radius: 5px;
            text-align: center;
        }

        .success {
            background-color: lightgreen;
            color: black;
        }
        .error {
            background-color: lightcoral;
            color: black;
        }

        .delete-product-btn {
            background-color: red;
        }

@media (max-width: 600px) {
    .container {
        padding: 10px;
        max-width: none;
    }

    input[type="text"],
    select,
    input[type="date"],
    input[type="file"],
    input[type="number"] {
        width: 100%;
    }

    table {
        font-size: 12px;
    }

    th, td {
        padding: 5px;
    }
}
    </style>
</head>

<body>
<form id="myForm" action="/outbound_order_submit" method="POST" enctype="multipart/form-data">

    <header>
        <h1><strong>录入出库单</strong></h1>
        <div id="message" style="display: none;"></div>
    </header>

    <div>
        <h2>单据信息:</h2>
    </div>

    <div>
        <label for="customer">客户:</label>
        <select name="customer" id="customer" onchange="get_product_list()">
            <option value="">请选择公司！</option>
            {% for customer_list in customer_list %}
            <option value="{{ customer_list[0] }}">{{ customer_list[1] }}</option>
            {% endfor %}
        </select>
        <br>
        <label for="enter_time">单据日期：</label>
        <input type="date" name="enter_time" id="enter_time">
        <br>
        <label for="doc_number">单据编号：</label>
        <input type="text" name="doc_number" id="doc_number" value="{{ current_datetime }}">
    </div>

    <div>
        <h2>产品信息：</h2>
        <table id="order_table">
            <thead>
            <tr>
                <th scope="col">选择产品</th>
                <th scope="col">产品名称</th>
                <th scope="col">产品型号</th>
                <th scope="col">产品颜色</th>
                <th scope="col">计量单位</th>
                <th scope="col">出库价格</th>
                <th scope="col">库存可用量</th>
                <th scope="col">出库数量</th>
                <th scope="col">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr>

                <td>
                    <label for="product_id1"></label>
                    <select name="product_id" id="product_id1" onchange="sendProductId(this)" class="product_id">
                        <option value="">请先选择客户！</option>
                    </select>
                </td>
                <td id="product_name1">N/A</td>
                <td id="product_model1">N/A</td>
                <td id="product_color1">N/A</td>
                <td id="product_unit1">N/A</td>
                <td id="sales_price1">N/A</td>
                <td id="quantity1" name="quantity">N/A</td>

                <td>
                    <div class="operation">
                        <input type="number" name="number" id="number">
                    </div>
                </td>
                <td>
                    <div class="operation">
                        <button type="button" value="" name="delete-product-btn" class="delete-product-btn"
                                onclick="deleteRow(this)">删除
                        </button>
                    </div>
                </td>
            </tr>
            </tbody>
            <colgroup>

            </colgroup>
        </table>
        <button type="button" value="" name="add-product-btn" class="add-product-btn" onclick="addRow()">添加产品
        </button>
    </div>

    <div>
        <h2>附件信息：</h2>
        <input type="file" name="fileInput" id="fileInput" multiple>
    </div>
    <div id="previewArea"></div>

    <div class="submit-button">
        <button type="submit" value="" name="submit">提交</button>
    </div>
</form>


<script>
    // 获取当前日期
    var today = new Date();

    // 将日期格式化为YYYY-MM-DD
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); // January is 0!
    var yyyy = today.getFullYear();
    today = yyyy + '-' + mm + '-' + dd;

    // 将默认值设置为当前日期
    document.getElementById('enter_time').value = today;



function addRow() {
    // 获取表格和最后一行
    var table = document.getElementById("order_table");
    var lastRow = table.rows[table.rows.length - 1];

    // 创建新行并设置单元格内容
    var newRow = document.createElement("tr");

    // 为新行中的元素添加带数字后缀的唯一 id
    var rowNumber = table.rows.length; // 获取当前行数作为数字后缀

    newRow.innerHTML = `
        <td>
            <label for="product_id${rowNumber}"></label>
            <select name="product_id" id="product_id${rowNumber}" onchange="sendProductId(this)" class="product_id">
            </select>
        </td>
        <td id="product_name${rowNumber}">N/A</td>
        <td id="product_model${rowNumber}">N/A</td>
        <td id="product_color${rowNumber}">N/A</td>
        <td id="product_unit${rowNumber}">N/A</td>
        <td id="sales_price${rowNumber}">N/A</td>
        <td id="quantity${rowNumber}">N/A</td>
        <td>
            <div class="operation">
                <input type="number" name="number" id="number">
            </div>
        </td>
        <td>
            <div class="operation">
                <button type="button" value="" name="delete-product-btn" class="delete-product-btn" onclick="deleteRow(this)">删除</button>
            </div>
        </td>
    `;

    // 将新行插入表格
    table.appendChild(newRow);

    // 执行get_product_list函数
    var selectedValue = document.getElementById("customer").value;
    var secondDropdown = document.getElementById("product_id" + rowNumber);

    fetch('/outbound_order_get_product_list?selected_value=' + selectedValue)
        .then(response => response.json())
        .then(data => {
            secondDropdown.innerHTML = ''; // 清空原有内容
            data.forEach(option => {
                var newOption = document.createElement('option');
                newOption.value = option.value;
                newOption.text = option.text;
                secondDropdown.appendChild(newOption);
            });
        });
    }


    function deleteRow(button) {
        var row = button.closest("tr");
        row.parentNode.removeChild(row);
    }

    function get_product_list() {
        var selectedValue = document.getElementById("customer").value;
        var secondDropdowns = document.getElementsByClassName("product_id");

        fetch('/outbound_order_get_product_list?selected_value=' + selectedValue)
            .then(response => response.json())
            .then(data => {
                // Convert HTMLCollection to array for easier iteration
                var dropdownArray = Array.from(secondDropdowns);

                dropdownArray.forEach(function (dropdown) {
                    dropdown.innerHTML = ''; // 清空原有内容
                    data.forEach(option => {
                        var newOption = document.createElement('option');
                        newOption.value = option.value;
                        newOption.text = option.text;
                        dropdown.appendChild(newOption);
                    });
                });
            });
    }

function sendProductId(selectElement) {
    var selectedValue = selectElement.value;
    var currentRow = selectElement.parentNode.parentNode; // 获取当前行
    var rowNumber = currentRow.rowIndex - 1; // 获取当前行的索引（减1是因为表头也算一行）

    fetch('/outbound_order_get_product_info?selected_value=' + selectedValue)
        .then(response => response.json())
        .then(data => {
            var productInfo = data[0]; // 获取第一个产品信息，即唯一的对象

            // 更新当前行的产品名称、型号、颜色等信息
            currentRow.cells[1].textContent = productInfo.product_name;
            currentRow.cells[2].textContent = productInfo.product_model;
            currentRow.cells[3].textContent = productInfo.product_color;
            currentRow.cells[4].textContent = productInfo.product_unit;
            currentRow.cells[5].textContent = productInfo.sales_price;
            currentRow.cells[6].textContent = productInfo.quantity;
        });
}


    // 监听文件选择事件
    document.getElementById('fileInput').addEventListener('change', function(event) {
        var files = event.target.files; // 获取选择的文件列表
        var previewArea = document.getElementById('previewArea');
        previewArea.innerHTML = ''; // 清空预览区域

        for (var i = 0; i < files.length; i++) {
            var file = files[i];

            if (file.type.startsWith('image/')) {
                // 如果是图片文件，创建一个<img>元素显示预览
                var img = document.createElement('img');
                img.src = URL.createObjectURL(file);
                img.width = 200;
                img.height = 200;
                previewArea.appendChild(img);
            } else {
                // 如果是其他文件，显示文件名
                var fileName = document.createTextNode(file.name);
                previewArea.appendChild(fileName);
            }

            previewArea.appendChild(document.createElement('br')); // 换行
        }
    });



$(document).ready(function(){
    $('#myForm').submit(function(e){
        e.preventDefault();

        $.ajax({
            type: 'POST',
            url: '/outbound_order_submit',
            data: new FormData(this),
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.message === '表单提交成功！') {
                    showSuccessMessage(response.message);
                } else {
                    showErrorMessage(response.message);
                }
            },
            error: function(xhr, status, error) {
                var err = JSON.parse(xhr.responseText);
                showErrorMessage(err.message);
            }
        });
    });

function showSuccessMessage(message) {
    window.scrollTo(0, 0); // 将页面滚动到顶部

    setTimeout(function() {
        $('#message').removeClass('error').addClass('success').text(message).show();
        setTimeout(function() {
            location.reload();
        }, 3000);
    }, 0);
}

    function showErrorMessage(message) {
    window.scrollTo(0, 0); // 将页面滚动到顶部
        $('#message').removeClass('success').addClass('error').text(message).show();
    }
});

</script>

</body>

</html>
